<template>
  <list-condition-template
    ref="table"
    :rows="rows"
    :total="total"
    @page-info-change="handlePageInfoChange"
    :search-data="listQuery.condition"
    :defaultSort="{ prop: 'createTime', order: 'descending' }"
  >
    <template slot="condition">
      <el-form-item prop="keyword">
        <el-input
          @keyup.enter.native="handleFilter"
          placeholder="名称或账号"
          v-model.trim="listQuery.condition.keyword"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="enable">
        <el-select
          v-model="listQuery.condition.enable"
          value-key="name"
          clearable
          placeholder="是否启用"
        >
          <el-option
            v-for="(item, key) in $CONST.ACTIVE_STATUS"
            :key="key"
            :label="item.title"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item prop="photoStudioId">
        <el-select
          v-model="listQuery.condition.photoStudioId"
          placeholder="影楼"
          filterable
          clearable
          :loading="selectLoading"
          @focus="getStudioSelect"
        >
          <el-option
            v-for="item in studios"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </template>
    <template slot="normalOperation">
      <el-form-item>
        <el-button
          class="filter-item"
          @click="handleCreate"
          type="success"
          icon="el-icon-plus"
          v-waves
          >新增</el-button
        >
      </el-form-item>
    </template>
    <template slot="columns">
      <el-table-column
        min-width="150px"
        label="账号"
        sortable="custom"
        property="account"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.account }}</span>
        </template>
      </el-table-column>
      <el-table-column
        min-width="150px"
        label="名称"
        align="center"
        sortable="custom"
        property="name"
      ></el-table-column>

      <el-table-column
        min-width="150px"
        label="电话"
        align="center"
        property="mobile"
      ></el-table-column>

      <el-table-column
        min-width="150px"
        label="影楼"
        align="center"
        property="photoStudio.name"
      ></el-table-column>

      <el-table-column
        class-name="status-col"
        align="center"
        label="状态"
        width="150px"
      >
        <template slot-scope="scope">
          <el-tag :type="scope.row.enable | showFilter">{{
            scope.row.enable ? "启用" : "禁用"
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        min-width="100"
        align="center"
        sortable="custom"
        property="createTime"
      ></el-table-column>
      <el-table-column
        label="更新时间"
        min-width="100"
        align="center"
        sortable="custom"
        property="updateTime"
      ></el-table-column>
      <el-table-column
        align="center"
        label="操作"
        width="240px"
        class-name="fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handleUpdate(scope.row)"
            v-waves
            >修改</el-button
          >
          <el-button
            size="mini"
            :type="scope.row.enable | showButtonFilter"
            @click="handleState(scope.row)"
            v-waves
            >{{ scope.row.enable ? "禁用" : "启用" }}</el-button
          >
          <el-button
            size="mini"
            type="info"
            @click="handleChangeUserPassword(scope.row)"
            v-waves
            >重置密码</el-button
          >
        </template>
      </el-table-column>
    </template>

    <el-dialog
      :title="changePassword.title"
      :visible.sync="changePassword.show"
      width="40%"
      @close="handleChangePasswordDialogClose"
    >
      <el-form
        size="mini"
        ref="changePasswordForm"
        :model="changePassword.formData"
        :rules="changePassword.rules"
        label-width="120px"
        status-icon
      >
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            placeholder="请输入密码"
            v-model="changePassword.formData.password"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPassword">
          <el-input
            type="password"
            placeholder="请再次输入密码"
            v-model="changePassword.formData.checkPassword"
            auto-complete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="changePassword.show = false"
          >取消</el-button
        >
        <el-button
          size="mini"
          type="primary"
          @click="handleDoChangeUserPassword"
          :loading="changePassword.loading"
          >{{ changePassword.loading ? "提交中" : "确定" }}</el-button
        >
      </span>
    </el-dialog>
  </list-condition-template>
</template>

<script>
import studioAPI from '@/api/photoStudio'
import studioUserAPI from '@/api/photoStudioUser'
import waves from '@/directive/waves' // 水波纹指令
import ListConditionTemplate from '@/components/templates/listConditionTemplate'

export default {
  directives: {
    waves
  },
  components: {
    ListConditionTemplate
  },
  data () {
    return {
      studios: [],
      selectLoading: false,
      rows: null,
      total: 0,
      listQuery: {
        condition: {
          keyword: null,
          status: null
        },
        pageInfo: null
      },
      changePassword: {
        formData: {
          password: '',
          checkPassword: '',
          id: ''
        },
        title: '修改密码',
        show: false,
        loading: false,
        rules: {
          password: [
            {
              required: true,
              validator: (rule, value, callback) => {
                if (value === '') {
                  callback(new Error('请输入密码'))
                } else if (value.length < 6 || value.length > 20) {
                  callback(new Error('密码长度需在6到20之间'))
                } else {
                  if (this.changePassword.formData.checkPassword !== '') {
                    this.$refs.changePasswordForm.validateField(
                      'checkPassword'
                    )
                  }
                  callback()
                }
              },
              trigger: 'blur'
            }
          ],
          checkPassword: [
            {
              required: true,
              validator: (rule, value, callback) => {
                if (value === '') {
                  callback(new Error('请再次输入密码'))
                } else if (value.length < 6 || value.length > 20) {
                  callback(new Error('密码长度需在6到20之间'))
                } else if (value !== this.changePassword.formData.password) {
                  callback(new Error('两次输入密码不一致'))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            }
          ]
        }
      }
    }
  },
  filters: {
    /**
     * 表格行显示状态过滤
     * @param {*} enable 显示状态
     */
    showFilter (enable) {
      return enable ? 'success' : 'danger'
    },
    /**
     * 表格按钮显示状态过滤
     * @param {*} show 显示状态
     */
    showButtonFilter (enable) {
      return enable ? 'danger' : 'success'
    }
  },
  methods: {
    /**
     * 查询影楼下拉框信息
     */
    getStudioSelect (keyword) {
      if (this.listQuery.condition.photoStudioId) {
        return
      }
      this.selectLoading = true
      studioAPI
        .getAll({ showLoading: false })
        .then((res) => {
          this.studios = res.data
          this.selectLoading = false
        })
        .catch((e) => {
          this.selectLoading = false
        })
    },
    /**
     * 加载数据
     */
    getList (pageInfo) {
      this.listQuery.pageInfo = pageInfo
      studioUserAPI.getPaged(this.listQuery).then((response) => {
        this.rows = response.data.content
        this.total = response.data.totalElements
      })
    },
    /**
     * 搜索条件变更处理
     */
    handleFilter () {
      this.$refs.table.changeCondition()
    },
    /**
     * 分页信息变动事件处理
     * @param  {Object} pageInfo 分页信息
     */
    handlePageInfoChange (pageInfo) {
      this.getList(pageInfo)
    },
    /**
     * 新增按钮点击处理
     */
    handleCreate () {
      this.$router.pushTo(this.$router.routesConfig.studioUserInfo)
    },
    /**
     * 修改按钮点击处理
     * @param {*} row 参数
     */
    handleUpdate (row) {
      this.$router.pushTo(this.$router.routesConfig.studioUserInfo, row.id)
    },
    /**
     * 启用、停用按钮点击处理
     * @param {*} row 参数
     */
    handleState (row) {
      const enabled = row.enable
      studioUserAPI
        .updateStatus({ id: row.id, enable: !enabled })
        .then((response) => {
          row.enable = !enabled
        })
    },
    /**
     * 重置密码按钮点击处理
     * @param {*} row 参数
     */
    handleChangeUserPassword (row) {
      this.changePassword.show = true
      this.changePassword.title = `重置密码 - ${row.account}`
      this.changePassword.formData.id = row.id
    },
    /**
     * 重置密码
     */
    handleDoChangeUserPassword () {
      this.$refs.changePasswordForm.validate().then((pass) => {
        if (pass) {
          this.changePassword.loading = true
          studioUserAPI
            .resetPassword({
              id: this.changePassword.formData.id,
              password: this.changePassword.formData.password,
              confirmPassword: this.changePassword.formData.checkPassword
            })
            .then((response) => {
              this.changePassword.loading = false
              this.changePassword.show = false
              this.changePassword.formData.id = null
              this.$notify({
                title: '成功',
                message: '密码重置成功',
                type: 'success'
              })
            })
            .catch((response) => {
              this.changePassword.loading = false
            })
        }
      })
    },
    /**
     * 重置密码对话框关闭事件处理
     */
    handleChangePasswordDialogClose () {
      this.$refs.changePasswordForm.resetFields()
    }
  }
}
</script>
